﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DevOnServer
{
    public class CWorldField
    {
        public CWorldField(CVec2Di pos)
        {
            Position = pos;
        }

        public void addObject(CWorldObject obj)
        {
            Objects.Add(obj);

            if (obj.Type == ObjType.Player)
                PlayerCount++;

            obj.Field = this;
        }

        public void removeObject(CWorldObject obj)
        {
            if (Objects.Contains(obj))
            {
                Objects.Remove(obj);

                if (obj.Type == ObjType.Player)
                    PlayerCount--;
            }
        }

        public void sendToAllPlayers(CPacket packet)
        {
            foreach (CWorldObject obj in Objects)
            {
                if (obj.Type == ObjType.Player)
                {
                    (obj as CPlayerObject).Player.Client.send(packet);
                }
            }
        }

        public void sendToAllPlayersBut(CPacket packet, CPlayerObject player)
        {
            foreach (CWorldObject obj in Objects)
            {
                if (obj.Type == ObjType.Player && obj != player)
                {
                    (obj as CPlayerObject).Player.Client.send(packet);
                }
            }
        }

        public void spawnAll(CPlayerObject player)
        {
            foreach (CWorldObject obj in Objects)
            {
                if (obj != player)
                {
                    player.Player.Client.send(CPacketCreator.spawn(obj));
                }
            }
        }

        public void despawnAll(CPlayerObject player)
        {
            foreach (CWorldObject obj in Objects)
            {
                if (obj != player)
                {
                    player.Player.Client.send(CPacketCreator.despawn(obj));
                }
            }
        }

        public bool isFieldInArea(CWorldField field)
        {
            return field.Position.X + 1 >= Position.X
                && field.Position.Y + 1 >= Position.Y
                && field.Position.X <= Position.X + 1
                && field.Position.Y <= Position.Y + 1;
        }

        public int PlayerCount { get; private set; }

        public List<CWorldObject> Objects = new List<CWorldObject>();

        public CVec2Di Position;
    }
}